<?php
/**
 * 统一异常接管
 */

namespace app;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\FuncNotFoundException;
use think\exception\ClassNotFoundException;
use think\exception\ErrorException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\template\exception\TemplateNotFoundException;
use think\db\exception\PDOException;
use think\db\exception\DbException;
use think\Response;
use Throwable;
use think\facade\Log;
use RuntimeException;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{


	private $error_log_db = true;	//异常日志是否写入数据库

    /**
     * Render an exception into an HTTP response.
     * @access public
     * @param \think\Request   $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {

        // 任何异常都记录日志,都存储到数据库
        Log::record('错误信息：'.print_r($e->getMessage(),true));
        Log::record('错误详情：'.print_r($e->getTraceAsString(),true));
        if($this->error_log_db){
            try {
                event('ExceptionLog', $e->getMessage());
            } catch (\Exception $e){
                return json([
                    'status'    =>  105,
                    'msg'       =>  '记录异常日志时发生错误，请检查数据库配置是否正确！',
                ]);

            }
        }

        // HTTP 异常
        if ($e instanceof HttpException) {
            return json([
                'status'    =>  $e->getStatusCode(),
                'msg'       =>  $e->getMessage()
            ]);
        }

        // 默认 生产环境使用
        // return json([
        //    'status'  =>  500,
        //    'msg'     =>  '服务器错误，请联系管理员处理！',
        // ]);

        // 默认 开发时使用
        return json([
            'status'    =>  $e->getCode(),
            'msg'       =>  $e->getMessage(),
            // 'data'      =>  $e->getTrace(),
        ]);

        return parent::render($request, $e);
    }



}
